<?php
/**
 * Created by PhpStorm.
 * User: HM22
 * Date: 2019/4/24
 * Time: 19:38
 */

namespace app\admin\controller;

use think\Db;
use my\Security;
use think\Validate;
use my\Tools;

class DriverWind extends Base
{
    protected $map = [];

    public function _initialize()
    {
        parent::_initialize();

    }

    //司机提现风控审核列表
    public function index()
    {
        $config['admin'] = session('admin_name');
        $config['url'] = url('table');
        $config['pay_type'] = input('get.pay_type') ?: 1; //提现方式 1 支付宝 2 微信 3 银行卡
        $config['check_status'] = [
            '1' => '待审核',
            '3' => '异常',
            '4' => '不通过'
        ];
        $config['driver_type'] = [
            '1' => '快车',
            '2' => '城际',
        ];

        $this->assign($config);
        return $this->fetch();
    }

    public function table()
    {
        $map['a.type'] = 2;  //1收入  2提现

        $page = input('get.page') ?: 1;
        $limit = input('get.limit') ?: 10;

        $field = "a.*,b.driver_phone,b.driver_name,c.bank_num as alipay_account,c.real_name as alipay_username";
        $res = Db::table('xm_driver_wallet a')
            ->join(['xm_driver' => 'b'], 'b.driver_id = a.driver_id', 'LEFT')
            ->join(['xm_driver_bank' => 'c'], 'c.driver_id = a.driver_id', 'LEFT')
            ->where($map)
            ->page($page, $limit)
            ->field($field)->order('a.id desc')->select();

        foreach ($res as $key => $value) {
            $res[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            $res[$key]['admin_time'] = $value['admin_time'] ? date('Y-m-d H:i:s', $value['admin_time']) : '';
            $res[$key]['money'] = sprintf("%.2f", abs($value['money']) / 100);

            if($value['admin_id']>0){
                $res[$key]['admin_name'] = 'admin_name';
            }

        }

        $count = Db::table('xm_driver_wallet a')
            ->where($map)->count();
        /*echo '<pre>';
        print_r($res);
        exit;*/
        echo json_encode([
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ]);
    }


    //申请提现 搜索
    public function searchIndex()
    {
        $page = input('get.page') ?: 1;
        $limit = input('get.limit') ?: 10;

        $map['a.type'] = 2; //提现
        $map['a.pay_type'] = 1;//提现方式 1 支付宝 2 微信 3 银行卡
        $map['a.is_pay'] = 0;

        $driver_name = trim(input('get.driver_name'));
        $driver_phone = trim(input('get.driver_phone'));
        $account_number = trim(input('get.account_number'));
        $driver_type = input('get.driver_type');
        $check_status = input('get.check_status');
        $start = strtotime(input('get.start'));
        $end = strtotime(input('get.end'));

        input('get.start') && $map['a.add_time'] = array('egt', $start);
        input('get.end') && $map['a.add_time'] = array('elt', $end);
        input('get.start') && input('get.end') && $map['a.add_time'] = array('between', array($start, $end));
        $driver_name && $map['driver_name'] = $driver_name;
        $driver_phone && $map['driver_phone'] = Security::encrypt($driver_phone);
        $account_number && $map['a.alipay_account'] = $account_number;
        $driver_type && $map['b.driver_type'] = $driver_type;

        if ($check_status) {
            $map['a.check_status'] = $check_status;
        } else {
            $map['a.check_status'] = ['neq', 2];
        }

        $field = "a.*,driver_phone,driver_name,b.driver_type";
        $res = Db::table('xm_driver_withdraw_flow a')
            ->join(['xm_driver_base' => 'b'], 'a.driver_id=b.driver_id', 'LEFT')
            ->where($map)
            ->page($page, $limit)
            ->field($field)->order('a.is_pay asc,a.id desc')->select();

        foreach ($res as $key => $value) {
            $res[$key]['driver_phone'] = Security::decrypt($value['driver_phone']);
            $res[$key]['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            $res[$key]['admin_time'] = $value['admin_time'] ? date('Y-m-d H:i:s', $value['admin_time']) : '';
            $res[$key]['money'] = sprintf("%.2f", abs($value['money']) / 100);
            $res[$key]['award_withdraw'] = sprintf("%.2f", abs($value['award_withdraw']) / 100);
            $res[$key]['balance_withdraw'] = sprintf("%.2f", abs($value['balance_withdraw']) / 100);
        }

        $count = Db::table('xm_driver_withdraw_flow a')
            ->join(['xm_driver_base' => 'b'], 'a.driver_id=b.driver_id', 'LEFT')
            ->where($map)->count();

        echo json_encode([
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ]);
    }

    //批量审核信息
    public function batchInfo()
    {
        //审核总条数
        $wait_check_count = Db::table('xm_driver_withdraw_flow')->where(['check_status' => 1, 'pay_type' => 1, 'type' => 2, 'is_pay' => 0])->count();

        $act = input('post.act') ?: '';
        if ($act == 'batch_deal') {
            $ids = input('post.ids') ?: '';

            if ($ids) {
                //异常条数
                $abnormal_count = $this->batchCheck($ids);
                //成功审核条数
                $success_count = $wait_check_count - $abnormal_count;
                exit(json_encode(['code' => 0, 'msg' => '审核完成', 'data' => ['success_count' => $success_count, 'abnormal_count' => $abnormal_count]]));

            } else {
                return ['code' => 1, 'msg' => '审核id为空'];
            }

        } else {
            //审核ids
            $ids = Db::table('xm_driver_withdraw_flow')->field('id')->where(['check_status' => 1, 'pay_type' => 1, 'type' => 2, 'is_pay' => 0])->select();
            $rows = [];
            foreach ($ids as $key => $value) {
                $rows[] = $value['id'];
            }
            $ids_str = implode(',', $rows);

            //已选择的 风控安全条件
            $safe_condition_select = Db::table('xm_driver_wind_config')->where('status', 1)->select();

            $this->assign('ids', $ids_str);
            $this->assign('safe_condition_select', $safe_condition_select);
            $this->assign('wait_check_count', $wait_check_count);
        }

        return $this->fetch();
    }

    //批量审核
    public function batchCheck($ids)
    {
        $map['type'] = 2;          // 1收入 2提现 3罚款
        $map['is_pay'] = 0;        //是否支付  0否 1是
        $map['check_status'] = 1;  //审核状态 1待审核 2已审核 3异常
        $pay_type = 1; //提现方式 1 支付宝 2 微信 3 银行卡
        $pay_type && $map['pay_type'] = $pay_type;
        $ids_arr = explode(',', $ids);
        $abnormal_count = 0;

        if ($pay_type == 1) {
            $field = "id,driver_id,money,balance_withdraw,award_withdraw,add_time,pay_type,is_pay,type,alipay_account,check_status";
            foreach ($ids_arr as $value) {
                $map['id'] = $value;
                //更新审核人员信息
                Db::table('xm_driver_withdraw_flow')->where($map)->update(['admin_id' => session('admin_id'), 'admin_name' => session('admin_name'), 'admin_time' => time()]);

                $res = Db::table('xm_driver_withdraw_flow')->field($field)->where($map)->order('id desc')->find();

                if ($res) {
                    //检查同一用户 是否存在多笔 待提现 或 异常数据
                    $flow_id_res = DB::table('xm_driver_withdraw_flow')->field('id')->where(['driver_id' => $res['driver_id'], 'check_status' => 2])->order('id DECS')->find();
                    $record_res = Db::table('xm_driver_withdraw_record')->field('id')->where(['flow_id' => $flow_id_res['id'], 'pay_status' => ['in', '1,4']])->find();  //1 待支付  4 支付异常

                    if ($record_res['id']) {
                        //更新为异常
                        Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '该用户已有一笔提现在处理中']);
                        $abnormal_count++;
                    } else {
                        //检查 钱包金额 是否大于等于 提现金额（冻结金额）
                        $wallet_res = Db::table('xm_driver_money')->field('money,freeze,award_balance,balance')->where(['driver_id' => $res['driver_id']])->find();
                        if ($wallet_res['money'] >= $wallet_res['freeze']) {
                            //申请提现金额 是否等于 冻结金额 && 冻结金额 大于0
                                if ($wallet_res['freeze'] == abs($res['money']) && $wallet_res['freeze'] > 0) {
                                    //检测 钱包里司机收入 奖励金额  大于等于  提现申请中的 司机收入提现 司机奖励提现
                                    if(($wallet_res['award_balance'] >= $res['award_withdraw']) && ($wallet_res['balance'] >= $res['balance_withdraw'])) {
                                        //验证支付宝账号正确性
                                        if ($res['alipay_account']) {
                                            //验证是否为 邮箱
                                            $is_email = Validate::is($res['alipay_account'], 'email');
                                            //验证提现支付宝账号格式 [手机号 和  邮箱]
                                            if ($is_email) {
                                                $rules = ['email' => 'email'];
                                                $msg = ['email' => '邮箱格式错误'];
                                                $data = ['email' => $res['alipay_account']];
                                            } else {
                                                $rules = ['phone' => 'require|max:11|regex:/^1[345789]\d{9}$/'];
                                                $msg = [
                                                    'phone.require' => '支付宝账号为空',
                                                    'phone.max' => '手机账号不能超过11个字符',
                                                    'phone.regex' => '支付宝账号手机格式不正确'
                                                ];
                                                $data = ['phone' => $res['alipay_account']];
                                            }
                                            $validate = new Validate($rules, $msg);
                                            $result = $validate->check($data);

                                            if (!$result) {
                                                //异常
                                                $abnormal_res = Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => $validate->getError()]);
                                                $abnormal_count++;
                                            } else {
                                                //查询司机id 是否在白名单的内 [白名单内为测试司机账号 禁止批量审核通过 只允许手动审核]
                                                $driver_white_list = Db::table('xm_white_list')->field('driver_str')->where('id',1)->find();
                                                $driver_white_arr = explode(',',$driver_white_list['driver_str']);
                                                
                                                if(in_array($res['driver_id'], $driver_white_arr)) {
                                                    //异常
                                                    Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '白名单中的司机，不允许批量审核通过,请手动审核']);
                                                    $abnormal_count++;
                                                } else {
                                                    //验证安全条件
                                                    $abnormal_content = [];
                                                    $abnormal_content = $this->check_safe_conditions($res, $abnormal_content);

                                                    if ($abnormal_content) {
                                                        //审核 不通过 或 异常
                                                        if (count($abnormal_content) > 1) {
                                                            $abnormal_content_str = implode(',', $abnormal_content);
                                                            $abnormal_res = Db::table('xm_driver_withdraw_flow')->where('id', $res['id'])->update(['check_status' => 3, 'abnormal_des' => $abnormal_content_str]);
                                                        } elseif (count($abnormal_content) == 1) {
                                                            $abnormal_res = Db::table('xm_driver_withdraw_flow')->where('id', $res['id'])->update(['check_status' => 3, 'abnormal_des' => $abnormal_content[0]]);
                                                        }
                                                        $abnormal_count++;
                                                    } else {
                                                        //审核成功
                                                        $success_res = Db::table('xm_driver_withdraw_flow')->where('id', $res['id'])->update(['check_status' => 2, 'abnormal_des' => '']);

                                                        //查询提现流水号
                                                        $out_trade_no = DB::table('xm_driver_wallet_record')->where('flow_id', $res['id'])->value('out_biz_no');
                                                        //添加 审核通过的数据 到 提现表记录 xm_driver_withdraw_record
                                                        $data = [
                                                            'flow_id' => $res['id'],
                                                            'add_time' => time(),
                                                            'is_pay' => 0,
                                                            'pay_status' => 1,
                                                            'w_common_id' => $out_trade_no,
                                                        ];
                                                        $insert_res = Db::table('xm_driver_withdraw_record')->insert($data);
                                                    }
                                                }
                                            }
                                        } else {
                                            $abnormal_res = Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '支付宝账号为空']);
                                            $abnormal_count++;
                                        }
                                    } else {
                                        Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '钱包司机收入与奖励收入小于提现中的收入提现和奖励提现']);
                                        $abnormal_count++;
                                    }
                            } else {
                                Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '提现金额与冻结金额不一致']);
                                $abnormal_count++;
                            }
                        } else {
                            Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '钱包余额小于提现金额']);
                            $abnormal_count++;
                        }
                    }
                } else {
                    //异常
                    $abnormal_res = Db::table('xm_driver_withdraw_flow')->where('id', $value)->update(['check_status' => 3, 'abnormal_des' => '参数错误']);
                    $abnormal_count++;
                }
            }

            return $abnormal_count;

        } elseif ($pay_type == 3) {
            return true;
        }
    }


    /** 验证安全条件
     * @param array $res
     */
    public function check_safe_conditions($data = [], $abnormal_content = [])
    {
        //风控安全条件
        $wind_condition = Db::table('xm_driver_wind_config')->select();
        foreach ($wind_condition as $item) {
            if ($item['status'] == 1 || $item['is_must'] == 1) {
                switch ($item['id']) {
                    case 1:   //1.校验提现司机信息的真实性
                        $check_result_1 = Db::table('xm_driver_base')->field('driver_id,auth_status,forbid,first_pass')->where('driver_id', $data['driver_id'])->find();
                        if (!$check_result_1 || $check_result_1['auth_status'] != 1 || $check_result_1['forbid'] != 2 || $check_result_1['first_pass'] != 1) {
                            $abnormal_content[] = $item['content'];
                        }
                        break;
                    case 2:  //2.提现信息过滤重复
                        $where['type'] = 2;          // 1收入 2提现 3罚款
                        $where['is_pay'] = 0;        //是否支付  0否 1是
                        $where['check_status'] = 1;  //审核状态 1待审核 2已审核 3异常
                        $where['pay_type'] = 1;//提现方式 1 支付宝 2 微信 3 银行卡
                        $where['alipay_account'] = $data['alipay_account'];

                        $check_result_2 = Db::table('xm_driver_withdraw_flow')->where($where)->count();
                        if ($check_result_2 > 1) {
                            $abnormal_content[] = $item['content'];
                        }
                        break;
                    case 3 : //3.单笔提现金额不在范围内  单位 分
                        if (abs($data['money']) < 1000 || abs($data['money'] > 100000)) {
                            $abnormal_content[] = $item['content'];
                        }
                        break;
                    case 4 :  //4.检测提现申请时间是否异常  每日9：00 - 18：00  可提现时间段
                        $add_time_res = Db::table('xm_driver_withdraw_flow')->field('add_time')->where('id', $data['id'])->find();
                        //获取申请时间的 小时数（不补0的）
                        $add_time_hour = date('G', $add_time_res['add_time']);
                        if (!$add_time_res || $add_time_hour < 9 || $add_time_hour >= 18) {
                            $abnormal_content[] = $item['content'];
                        }
                        break;
                    case 5 :  // 5.检测提现司机是否有收入流水，是否有已完成的行程
                        //已完成的订单记录
                        $order_recode = Db::table('xm_order_common')->field('common_id')->where(['is_del' => 2, 'order_status' => ['in','40,50'], 'driver_id' => $data['driver_id']])->find();
                        //车主收入流水
                        $recharge_recode = Db::table('xm_driver_wallet_record')->field('record_id')->where(['record_type' => 1,'driver_id' => $data['driver_id']])->find();
                        //司机奖励
                        $driver_award_recode = Db::table('xm_driver_wallet_record')->field('record_id')->where(['record_type' => 4,'driver_id' => $data['driver_id']])->find();

                        if (!$recharge_recode && !$order_recode && !$driver_award_recode) {
                            $abnormal_content[] = $item['content'];
                        }
                        break;
                    case 6 : //6.检测是否为城际司机（城际司机暂不支持提现）
                        $allow_driver_type = Db::table('xm_driver_base')->field('driver_type')->where(['driver_id'=> $data['driver_id']])->find();

                        if($allow_driver_type['driver_type'] != 1) {
                            $abnormal_content[] = $item['content'];
                        }
                        break;
                    default:;
                }
            }

        }
        return $abnormal_content;
    }

    //单个手动审核
    public function singleCheck()
    {
        $id = input('get.id');
        $res = Db::table('xm_driver_wallet w')
            ->field('w.*,b.driver_phone,b.driver_name,c.bank_num as alipay_account,c.real_name as alipay_username')
            ->join(['xm_driver' => 'b'], 'b.driver_id=w.driver_id')
            ->join(['xm_driver_bank' => 'c'], 'c.driver_id=w.driver_id')
            ->where('w.id', $id)->find();

        $res['admin_time'] = $res['admin_time'] ? date('Y-m-d H:i:s', $res['admin_time']) : '';
        $res['money'] = sprintf("%.2f", abs($res['money']) / 100) . '元';
        $res['audit_status'] = '<span style="color: red;">' . check_status()[$res['check_status']] . '</span>';
        $res['abnormal_des'] = explode(',', $res['abnormal_des']);

        $res['pay_type'] = '支付宝';
        $fields = [
            'id' => '编号ID',
            'driver_name' => '姓名',
            'driver_phone' => '手机号',
            'alipay_username' => '支付宝姓名',
            'alipay_account' => '支付宝账号',
            'money' => '提现金额',
            'check_status' => '审核状态',
            'abnormal_des' => '异常原因',
            'admin_name' => '审核人员',
            'admin_time' => '处理日期',
        ];

        $this->assign('info', $res);
        $this->assign('fields', $fields);

        return $this->fetch();
    }

    //确认审核
    public function submits()
    {
        $id = input('post.id');
        $remark = input('post.remark');
        $audit_status = input('post.audit_status');


        if (!$id || !$_SESSION['admin_id']) {
            exit(json_encode(['code' => 0, 'msg' => '参数错误']));
        }

        if (empty($remark)) {
            exit(json_encode(['code' => 0, 'msg' => '审核备注不能为空']));
        }

        //更新审核状态
        $res = Db::table('xm_driver_wallet')->where('id', $id)->update(['audit_status' => $audit_status, 'admin_id' => $_SESSION['admin_id'], 'admin_name' => $_SESSION['admin_name'], 'admin_time' => time(), 'remark' => $remark]);

        if ($audit_status == 1) {
            exit(json_encode(['code' => 1, 'msg' => '审核完成']));
            //查询提现流水号
           /* $out_trade_no = DB::table('xm_driver_wallet_record')->where('flow_id', $id)->value('out_biz_no');

            //若通过 添加 审核通过的数据 到 提现表记录 xm_driver_withdraw_record
            $data = [
                'flow_id' => $id,
                'add_time' => time(),
                'is_pay' => 0,
                'pay_status' => 1,
                'w_common_id' => $out_trade_no,
            ];
            $insert_res = Db::table('xm_driver_withdraw_record')->insertGetId($data);

            if ($insert_res) {
                exit(json_encode(['code' => 1, 'msg' => '审核完成']));
            } else {
                exit(json_encode(['code' => 0, 'msg' => '待提现记录更新失败']));
            }*/
        } elseif ($audit_status == 9) {
            $driverWallet = Db::table('xm_driver_wallet')->where('id', $id)->find();
            $driverMoney = Db::table('xm_driver_money')->where('driver_id', $driverWallet['driver_id'])->find();
            //审核失败时 清空钱包冻结金额
            //提现金额
            //这里要判断，懒！！！
            $freeze=$driverMoney['freeze']-$driverWallet['money'];

            //这里要判断，懒！！！
            $money=$driverMoney['money']+$driverWallet['money'];

            $result = Db::table('xm_driver_money')
                ->where('driver_id', $driverWallet['driver_id'])
                ->update(['freeze' => $freeze,'money' => $money]);

            if ($result) {
                //$phone = Db::table('xm_driver_base')->where('driver_id', $driverWallet['driver_id'])->value('driver_phone');
                //**给用户推送一条信息
                exit(json_encode(['code' => 1, 'msg' => '审核完成']));
            } else {
                exit(json_encode(['code' => 0, 'msg' => '审核失败']));
            }
        }

    }

    //风控
    public function wind()
    {
        $config['url'] = url('windConfig');
        $this->assign($config);
        return $this->fetch();
    }

    //风控审核条件
    public function windConfig()
    {
        $page = input('get_page') ?: 1;
        $limit = input('get.limit') ?: 10;

        $res = Db::table('xm_driver_wind_config')->page($page, $limit)->select();
        $count = Db::table('xm_driver_wind_config')->count();

        echo json_encode([
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'data' => $res
        ]);
    }

    //开启或关闭条件
    public function cancel()
    {
        $map['id'] = input('post.id');
        if (empty($map['id'])) {
            return json(array('status' => 0, 'msg' => '缺少参数'));
        }
        $status = input('post.status') == 1 ? 2 : 1;

        $info = Db::table('xm_driver_wind_config')->where($map)->find();

        if ($info['is_must'] == 1) {
            //若为必须条件 状态必为开启状态
            if ($status == 1) {
                Db::table('xm_driver_wind_config')->where($map)->update(array('status' => 1));
            } else {
                return json(array('status' => 0, 'msg' => '必须条件，请勿关闭!'));
            }
        } else {
            $res = Db::table('xm_driver_wind_config')->where($map)->update(array('status' => $status));

            if (empty($res)) {
                return json(array('status' => 0, 'msg' => '操作失败'));
            }
        }
        return json(array('status' => 1, 'msg' => '操作成功'));
    }

}